<script setup lang="ts">
import {onMounted, reactive, ref, watchEffect} from 'vue'
import type {Equipment, AddAndEditEquipment, PageEquipment, PageResp} from "@/type/equipment.ts";
import {createEquipment, deleteEquipment, getEquipmentById, getPageEquipments, updateEquipment} from "@/api/equipment";
import {ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadProps} from "element-plus";

// 查询-下拉框+输入框数据
const input = ref('')
const select = ref('3')

// 分页-当前页码+一页多少条数据+总数据量
const currentPage = ref(1)
const pageSize = ref(6)
const total = ref(20)

// 表格数据
const parentBorder = ref(false)
const tableData = ref<Equipment[]>([])

// 分页查询设备
const getPageEquipment = async () => {
  const pageInfo: PageEquipment = {
    equipmentId: select.value == '1' ? Number(input.value) : null,
    equipmentName: select.value == '2' ? input.value : '',
    equipmentType: select.value == '3' ? input.value : '',
    status: select.value == '4' ? input.value : '',
    page: currentPage.value,
    pageSize: pageSize.value
  }
  console.log(pageInfo)
  const result: PageResp = await getPageEquipments(pageInfo)
  if (result.code == 1) {
    total.value = result.data.total
    tableData.value = result.data.records
  }
}

// 挂载时查询一次
onMounted(() => {
  console.log(currentPage.value, pageSize.value)
  getPageEquipment()
})

// 监控查询变量-有变则重新查询
watchEffect(() => {
  getPageEquipment()
})

// 删除设备
const delEquipment = (id: number) => {
  ElMessageBox.confirm(
      '确定要删除此设备?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
  )
      .then(async () => {
        try {
          const result = await deleteEquipment(id); // 调用删除接口
          if (result.code === 1) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            });
            await getPageEquipment(); // 刷新列表
          } else {
            // 处理错误情况
            ElMessage({
              type: 'error',
              message: result.message || '删除失败，请稍后重试。',
            });
          }
        } catch (error) {
          // 捕获网络请求或其他异常
          ElMessage({
            type: 'error',
            message: '删除失败，请检查网络或稍后重试。',
          });
        }
      })
      .catch(() => {
        // 用户取消删除操作
        ElMessage({
          type: 'info',
          message: '删除取消',
        });
      });
};


// Dialog数据
const DialogVisible = ref(false)
const DialogTitle = ref('新增设备')
const addOrEdit = ref(1)  // Dialog是新增(0)还是修改(>0)即同时代表修改的设备id

// Dialog中表单数据
const DialogFormData = reactive<AddAndEditEquipment>({
  equipmentId: -1,
  equipmentName: '',
  equipmentType: '',
  status: '',
  image: '',
})

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
    if (rawFile.size < 4194304) {
      return true
    } else {
      ElMessage.error('上传文件必须小于 4M')
      return false
    }
  } else {
    ElMessage.error('上传文件必须是 png | img | gif')
    return false
  }
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  DialogFormData.image = response.data
}

// 表单校验
const ruleFormRef = ref<FormInstance>()
// 规则
const checkInput = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('不可为空,请输入...'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<AddAndEditEquipment>>({
  equipmentId: [{ validator: checkInput, trigger: 'blur' }],
  equipmentName: [{ validator: checkInput, trigger: 'blur' }],
  equipmentType: [{ validator: checkInput, trigger: 'blur' }],
  status: [{ validator: checkInput, trigger: 'blur' }],         //需要设置为选项
  image: []
})

// 新增设备
const addEquipment = () => {
  DialogTitle.value = '新增设备'
  addOrEdit.value = 0

  // 先清空表单数据
  DialogFormData.equipmentName = ''
  DialogFormData.equipmentType = ''
  DialogFormData.status = ''
  DialogFormData.image = ''

  DialogVisible.value = true
}

// 修改设备
const editEquipment = async (id: number) => {
  DialogTitle.value = '修改设备'
  addOrEdit.value = id

  // 先将数据回显至表单
  // 用addOrEdit.value查询
  // 调用查询单个设备api
  const result = await getEquipmentById(addOrEdit.value)
  if (result.code == 1) {
    DialogFormData.equipmentId = result.data.equipmentId
    DialogFormData.equipmentName = result.data.equipmentName
    DialogFormData.equipmentType = result.data.equipmentType
    DialogFormData.status = result.data.status
    DialogFormData.image = result.data.image
  }

  DialogVisible.value = true
}
// 提交Dialog中的表单，新增或者修改
const confirm = async () => {
  if (addOrEdit.value > 0) {
    const result = await updateEquipment((DialogFormData as AddAndEditEquipment))
    if (result.code == 1) {
      ElMessage.success('编辑成功')
    }
  } else {
    const addFormData: Omit<AddAndEditEquipment, 'equipmentId'> = {
      equipmentName: DialogFormData.equipmentName,
      equipmentType: DialogFormData.equipmentType,
      status: DialogFormData.status,
      image: DialogFormData.image,
    }
    const result = await createEquipment(addFormData)
    if (result.code == 1) {
      ElMessage.success('新增成功')
    }
  }

  DialogVisible.value = false

  // 成功操作后更新表内容-再次分页查询
  await getPageEquipment()
}
</script>

<template>
  <div class="equipment-container">
    <!--主要操作展示区-->
    <el-card>
      <div class="header-add-and-find">
                <!--左侧新增设备按钮-->
                <el-button type="primary" @click="addEquipment">新增设备</el-button>
<!--        右侧查询设备按钮-->
        <el-input
            v-model="input"
            clearable
            prefix-icon="Search"
            style="max-width: 600px"
            placeholder="（实时搜索）请输入"
            class="input-with-select"
        >

          <template #prepend>
            <el-select v-model="select" placeholder="Select" style="width: 115px">
              <el-option label="设备id" value="1"/>
              <el-option label="设备名字" value="2"/>
              <el-option label="设备类型" value="3"/>
              <el-option label="状态" value="4"/>
            </el-select>
          </template>
        </el-input>
      </div>
      <!--      <div class="info-main">-->
      <!--        <el-table :data="tableData" :border="parentBorder" max-height="445" table-layout="fixed" style="width: 100%">
                &lt;!&ndash;详细数据展开&ndash;&gt;
                <el-table-column type="expand">
                  <template #default="props">
                    <div class="detail-info" style="display: flex; justify-content: center">
                      <el-card
                          style="margin: 20px; width: 75%; border-radius: 12px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">
                        <div style="display: flex;">
                          &lt;!&ndash; 左侧：图片 &ndash;&gt;
                          <div
                              style="flex: 0 0 150px; display: flex; justify-content: center; align-items: center; padding: 20px;">
                            <el-image :src="props.row.imageUrl" style="width: 120px; height: 120px; border: 2px solid #eee;"></el-image>
                          </div>
                          &lt;!&ndash; 右侧：详细信息 &ndash;&gt;
                          <div style="flex: 1; padding: 20px;">
                            <h2 style="margin: 0 0 10px; font-size: 24px; color: #333;">{{ props.row.equipmentName }}</h2>
                            <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                              <p style="margin: 0; font-size: 16px; color: #666;"><strong>ID:</strong> {{ props.row.equipmentId }}
                              </p>
                              <p style="margin: 0; font-size: 16px; color: #666;"><strong>类别:</strong> {{
                                  props.row.category
                                }}</p>
                              <p style="margin: 0; font-size: 16px; color: #666;"><strong>状态:</strong> {{
                                  props.row.status
                                }}</p>
                              <p style="margin: 0; font-size: 16px; color: #666;"><strong>购买日期:</strong>
                                {{ props.row.purchaseDate }}</p>
                              <p style="margin: 0; font-size: 16px; color: #666;"><strong>上次维护日期:</strong>
                                {{ props.row.lastMaintenanceDate }}</p>
                            </div>
                            <p style="margin: 10px 0 0; font-size: 16px; color: #666;"><strong>描述:</strong>
                              {{ props.row.description }}</p>
                          </div>
                        </div>
                      </el-card>
                    </div>
                  </template>
                </el-table-column>-->


      <el-table :data="tableData" :border="parentBorder" max-height="445" table-layout="fixed" style="width: 100%">
        <!--表格展示-->
        <el-table-column label="ID" prop="equipmentId" align="center" width="100px"/>
        <el-table-column label="图片" align="center" width="150px">
          <template #default="props">
            <el-image :src="props.row.image" style="width: 100px; height: 100px;"/>
          </template>
        </el-table-column>
        <el-table-column label="设备id" prop="equipmentId" align="center" width="150px"/>
        <el-table-column label="设备名字" prop="equipmentName" align="center" width="150px"/>
        <el-table-column label="设备类型" prop="equipmentType" align="center" width="150px"/>
        <el-table-column label="状态" prop="status" align="center" width="150px"/>
                  <el-table-column label="操作" align="center">
                    <template #default="props">
                      <el-button type="primary" icon="Edit" color="#E6A23C" @click="editEquipment(props.row.equipmentId)">修改
                      </el-button>
                      <el-button type="primary" icon="Delete" color="#F56C6C" @click="delEquipment(props.row.equipmentId)">删除
                      </el-button>
                    </template>
                  </el-table-column>
      </el-table>


      <!--分页-->
      <div class="pagination-block">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[6, 8, 10, 12, 14]"
            layout="prev, pager, next, jumper, ->,sizes, total"
            :total="total"
            :background="true"
        />
      </div>

<!--            </div>-->
    </el-card>


        <!--Dialog-->
        <el-dialog
            v-model="DialogVisible"
            class="add-edit-dialog"
            width="500px"
            align-center
            :show-close="false"
        >
          <template #header>
            <div class="dialog-title">
              {{ DialogTitle }}
            </div>
          </template>
          <!-- 表单 -->
          <el-form
              ref="ruleFormRef"
              :model="DialogFormData"
              :rules="rules"
              label-width="100px"
              label-position="left"
              size="default"
              status-icon
              class="dialog-form"
          >
            <el-form-item label="名称" prop="equipmentName">
              <el-input v-model="DialogFormData.equipmentName" placeholder="请输入名称"/>
            </el-form-item>
            <el-form-item label="类型" prop="equipmentType">
              <el-input
                  v-model="DialogFormData.equipmentType"
                  placeholder="请输入类型"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-input v-model="DialogFormData.status" placeholder="请输入状态"/>
            </el-form-item>
            <el-form-item label="图片">
              <el-upload
                  :before-upload="beforeAvatarUpload"
                  :data="{ type: 3 }"
                  :on-success="handleAvatarSuccess"
                  :show-file-list="false"
                  action="http://localhost:8080/files/upload"
                  class="image-uploader"
              >
                <img v-if="DialogFormData.image" :src="DialogFormData.image" class="image"/>
                <el-icon v-else class="image-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-form>
          <!-- 底部按钮 -->
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="DialogVisible = false">取消</el-button>
              <el-button type="primary" @click="confirm">提交</el-button>
            </div>
          </template>
        </el-dialog>
  </div>
</template>

<style lang="scss">
</style>












